﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using DevExpress.XtraGrid.Views.Grid;

namespace CIRDiagnoseDevice.DBManage
{
    class TestRecordManage
    {
        private string serverPath;
        private string password;
        private string connStr;
        private SqlConnection _sqlConn;
        /// <summary>
        /// 数据库连接地址
        /// </summary>
        public string ServerPath
        {
            get { return serverPath; }
            set { serverPath = value; }
        }

        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        public TestRecordManage()
        {
            GetDBAddress();
        }

        private void GetDBAddress()
        {
            ReadiniFile read = new ReadiniFile(Application.StartupPath);
            List<string> dbInfo = read.ReadDBConnectionInfo();
            this.Password = dbInfo[1];
            this.ServerPath = dbInfo[0];
        }

        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public string CreateDB(string dbName)
        {
            try
            {
                connStr = "data source=" + ServerPath + ";user id=sa;password= " + Password + ";persist security info=false;packet size=4096";
                string sql = "IF NOT EXISTS (SELECT * FROM SYSDATABASES WHERE NAME ='" + dbName + "') " +
                                   "CREATE DATABASE " + dbName + ";";
                ExecuteSql(connStr, sql);
                return dbName;
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="Sql"></param>
        private void ExecuteSql(string conn, string Sql)
        {
            System.Data.SqlClient.SqlConnection mySqlConnection =
               new System.Data.SqlClient.SqlConnection(conn);
            System.Data.SqlClient.SqlCommand Command =
               new System.Data.SqlClient.SqlCommand(Sql, mySqlConnection);
            Command.Connection.Open();
            try
            {
                Command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                //  MessageBox.Show(e.Message);
            }
            finally
            {
                Command.Connection.Close();
            }
        }
        public bool ExecuteSql(string Sql)
        {
            bool sucess = false;
            System.Data.SqlClient.SqlCommand Command =
             new System.Data.SqlClient.SqlCommand(Sql, _sqlConn);
            try
            {
                Command.ExecuteNonQuery();
                sucess = true;
                return sucess;
            }
            catch (Exception e)
            {
                //  MessageBox.Show(e.Message);
                return sucess;
            }
            finally
            {
                Command.Connection.Close();
            }

        }
        /// <summary>
        ///  根据表记录进行更新
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="batchSize"></param>
        /// <returns></returns>
        public bool DataUpdateTestConfig(DataTable dt, int batchSize)
        {
            int count = dt.Rows.Count;
            bool flag = false;
            try
            {

                DataTable dg = new DataTable();

                #region fangfa4
                // DataTable shuttleTable = new DataTable();
                // shuttleTable = dt.Clone();
                //  shuttleTable.AcceptChanges();
                // shuttleTable = dt;
                // //DataRow row; 
                // //int tempShuttleID = 1; 
                // //tempShuttleID++; 
                // //row = shuttleTable.NewRow(); 
                // //row["标识"] = 1; 
                // //shuttleTable.Rows.Add(row); 
                // //需要使用AcceptChanges()函数 
                // shuttleTable.AcceptChanges(); 
                //// shuttleTable = dt;
                // //接下来，填充其它数据，这时候喜欢已经认为是update状态了 
                //// shuttleTable.Rows[0]["方向编号"] = 19; 
                // //第二步：（同insert） 
                // //构造SqlDataAdapter  
                // //SqlConnection conn = new SqlConnection("Data  Source=JFSYS-PEIJIHUI;Initial Catalog=BTRC_2;User ID=sa;Password=sa2006sa; Connect Timeout=10");
                // //conn.Open();
                // SqlDataAdapter adapter = new SqlDataAdapter();
                // //第三步： 
                // adapter.UpdateCommand = new SqlCommand("update tb_TestIndexConfig set minimum=@minimum ,maxnum=@maxnum where TestGroup=@TestGroup and TestName=@TestName", _sqlConn );
                // //adapter.UpdateCommand.Parameters.Add("@标识", SqlDbType.Int, 10, "标识");
                // //adapter.UpdateCommand.Parameters.Add("@方向编号", SqlDbType.Int, 10, "方向编号");
                // adapter.UpdateCommand.Parameters.Add("@minimum", SqlDbType.Float, 8, "指标最低值");
                // adapter.UpdateCommand.Parameters.Add("@maxnum", SqlDbType.Float, 8, "指标最高值");
                // adapter.UpdateCommand.Parameters.Add("@TestGroup", SqlDbType.NVarChar, 50, "分类");
                // adapter.UpdateCommand.Parameters.Add("@TestName", SqlDbType.NVarChar, 50, "测试项目");
                // //更新 
                // adapter.Update(shuttleTable);

                #endregion
                #region fangfa3
                // string emailSql = "select TestGroup, TestName, unit, minimum, maxnum,exponent,remark from tb_TestIndexConfig";
                // DataSet emailAdd = new DataSet();
                // SqlDataAdapter emailAdapter = new SqlDataAdapter(emailSql, _sqlConn);
                // SqlCommandBuilder cb = new SqlCommandBuilder(emailAdapter);
                // emailAdapter.Fill(emailAdd, "address");
                //// myConn.Close();
                // DataTable myDt = emailAdd.Tables["address"];
                // myDt.PrimaryKey = new DataColumn[] { myDt.Columns["email"] };
                // //修改myDs数据

                // emailAdapter.Update(emailAdd, "address");

                #endregion
                #region 方法2
                DataSet dsPubs = new DataSet("Pubs");

                SqlCommand sqlcmd = new SqlCommand("select TestGroup, TestName, unit, userminimum, usermaximum,exponent,remark from tb_TestIndexConfig", _sqlConn);
                SqlDataAdapter sda = new SqlDataAdapter(sqlcmd);
                sda.FillSchema(dsPubs, SchemaType.Source, "Authors");
                sda.Fill(dsPubs, "Authors");
                Object[] objs = new Object[] { 0, 0 };
                DataRow currow;
                object exponent;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    objs[0] = dt.Rows[i]["分类"];
                    objs[1] = dt.Rows[i]["测试项目"];
                    currow = dsPubs.Tables["Authors"].Rows.Find(objs);
                    if (currow == null)
                    {
                        continue;
                    }
                    currow["userminimum"] = dt.Rows[i]["指标最低值"];
                    currow["usermaximum"] = dt.Rows[i]["指标最高值"];
                    exponent = dt.Rows[i]["科学计数单位"];
                    currow["exponent"] = ((exponent == null) || (exponent.ToString().Trim() == "") ? 0 : exponent);
                    currow["remark"] = dt.Rows[i]["备注"];
                }
                SqlCommandBuilder sqlcmdB = new SqlCommandBuilder(sda);
                sda.Update(dsPubs, "Authors");
                #endregion

                flag = true;
            }
            catch (Exception ex)
            {
                // LogHelper.Error(ex.Message);
                return false;
            }
            return flag;
        }
        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="sql"></param>
        public void CreateTable(string dbName, string sql)
        {
            connStr = "server =" + serverPath + ";database = " + dbName + "; User ID = sa; Password = " + Password;
            ExecuteSql(connStr, sql);
        }
        /// <summary>
        /// 将测试结果保存到数据库
        /// </summary>
        /// <param name="testtime"></param>
        /// <param name="modulName"></param>
        /// <param name="tester"></param>
        /// <returns></returns>
        public bool RestoreData(DataTable dt, string sqltablename)
        {
            bool result = true;
            connStr = "server =" + serverPath + ";database = testResult; User ID = sa; Password = " + Password;
            SqlConnection sqlConn = new SqlConnection(connStr);
            SqlBulkCopy bulCopy = new SqlBulkCopy(sqlConn);
            bulCopy.DestinationTableName = sqltablename;//"test_rec";
            bulCopy.BatchSize = dt.Rows.Count;
            try
            {
                sqlConn.Open();
                if (dt != null && dt.Rows.Count != 0)
                    bulCopy.WriteToServer(dt);
            }
            catch (Exception e)
            {
                result = false;
            }
            finally
            {
                sqlConn.Close();
                if (bulCopy != null)
                    bulCopy.Close();
            }
            return result;
        }
        /// <summary>
        /// 打开数据库
        /// </summary>
        /// <returns></returns>
        public void OpenDataBase()
        {
            connStr = "server =" + serverPath + ";database = testResult; User ID = sa; Password = " + Password;
            _sqlConn = new SqlConnection(connStr);
            try
            {
                _sqlConn.Open();
            }
            catch (Exception ex)
            {


            }

        }
        public DataTable ExecuteSqlTable(string Sql)
        {
            try
            {
                DataSet ds = new DataSet();
                SqlDataAdapter sda = new SqlDataAdapter(Sql, _sqlConn);
                SqlCommandBuilder cb = new SqlCommandBuilder(sda);
                sda.Fill(ds, "table");
                // myConn.Close();
                return ds.Tables["table"];
            }
            catch (Exception)
            {

                return null;
            }


        }
        /// <summary>
        /// 关闭数据库
        /// </summary>
        /// <returns></returns>
        public void CloseDataBase()
        {
            _sqlConn.Close();
            _sqlConn.Dispose();
        }

        public object ExecuteSqlScalar(string Sql)
        {
            System.Data.SqlClient.SqlCommand Command =
                 new System.Data.SqlClient.SqlCommand(Sql, _sqlConn);
            try
            {
                return Command.ExecuteScalar();
            }
            catch
            { return null; }
        }
        public int ExecuteSqlNone(string Sql)
        {
            System.Data.SqlClient.SqlCommand Command =
                 new System.Data.SqlClient.SqlCommand(Sql, _sqlConn);
            try
            {
                return Command.ExecuteNonQuery();
            }
            catch
            { return 0; }
        }
        /// <summary>
        /// 将已经测试过的设备信息保存到数据库
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public bool RestoreData(string dev_num, DeviceType type)
        {
            bool result = true;
            connStr = "server =" + serverPath + ";database = testResult; User ID = sa; Password = " + Password;
            SqlConnection sqlConn = new SqlConnection(connStr);
            string sqlStr = "Select * From deviceInfo Where deviceInfo.CIR编号 = '" + dev_num + "'";
            SqlCommand command = new SqlCommand();
            command.CommandText = sqlStr;
            command.Connection = sqlConn;
            try
            {
                sqlConn.Open();
                int resultRow = command.ExecuteNonQuery();
                if (resultRow > 0)
                {
                    return result;
                }
                else
                {
                    result = InsertSQL(dev_num, command, type);
                    return result;
                }
            }
            catch (Exception e)
            {
                result = false;
            }
            finally
            {
                sqlConn.Close();
            }
            return result;
        }

        private bool InsertSQL(string dev_num, SqlCommand command, DeviceType type)
        {
            string insertStr = "Insert into deviceInfo(机车属局,机车属段,机车属所,机车编号,机车端别,机车修程," +
                                                           "CIR属局,CIR属段,CIR属车间,CIR属工区,CIR生产商,CIR型号,CIR编号,CIR修程)" +
                                                           "Values(@cab_bur,@cab_seg,@cab_pl,@cab_num,@cab_db,@cab_xc," +
                                                           "@dev_bur,@dev_seg,@dev_ws,@dev_wa,@dev_man,@dev_mod,@dev_num,@dev_xc)";
            command.CommandText = insertStr;
            command.Parameters.Add("@cab_bur", SqlDbType.NVarChar);
            command.Parameters["@cab_bur"].Value = MainFrm.device.Cab_bur;
            command.Parameters.Add("@cab_seg", SqlDbType.NVarChar);
            command.Parameters["@cab_seg"].Value = MainFrm.device.Cab_seg;
            command.Parameters.Add("@cab_pl", SqlDbType.NVarChar);
            command.Parameters["@cab_pl"].Value = MainFrm.device.Cab_pl;
            command.Parameters.Add("@cab_num", SqlDbType.NVarChar);
            command.Parameters["@cab_num"].Value = MainFrm.device.Cab_num;
            command.Parameters.Add("@cab_db", SqlDbType.Int);
            command.Parameters["@cab_db"].Value = MainFrm.device.Cab_db;
            command.Parameters.Add("@cab_xc", SqlDbType.NVarChar);
            command.Parameters["@cab_xc"].Value = MainFrm.device.Cab_xc;
            command.Parameters.Add("@dev_bur", SqlDbType.NVarChar);
            command.Parameters["@dev_bur"].Value = MainFrm.device.Dev_bur;
            command.Parameters.Add("@dev_seg", SqlDbType.NVarChar);
            command.Parameters["@dev_seg"].Value = MainFrm.device.Dev_seg;
            command.Parameters.Add("@dev_ws", SqlDbType.NVarChar);
            command.Parameters["@dev_ws"].Value = MainFrm.device.Dev_ws;
            command.Parameters.Add("@dev_wa", SqlDbType.NVarChar);
            command.Parameters["@dev_wa"].Value = MainFrm.device.Dev_wa;
            command.Parameters.Add("@dev_man", SqlDbType.NVarChar);
            if (type == DeviceType.CIR)
            {
                command.Parameters["@dev_man"].Value = MainFrm.device.Dev_man;
            }
            if (type == DeviceType.LBJ)
            {
                command.Parameters["@dev_man"].Value = MainFrm.MotherFrm.LbjManufName;
            }
            command.Parameters.Add("@dev_mod", SqlDbType.NVarChar);
            command.Parameters["@dev_mod"].Value = MainFrm.device.Dev_mod;
            command.Parameters.Add("@dev_num", SqlDbType.NVarChar);
            command.Parameters["@dev_num"].Value = MainFrm.device.Dev_num;
            command.Parameters.Add("@dev_xc", SqlDbType.NVarChar);
            command.Parameters["@dev_xc"].Value = MainFrm.device.Dev_xc;
            int resultRow = command.ExecuteNonQuery();
            if (resultRow > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 创建数据表结构
        /// </summary>
        /// <param name="isTestRecord"></param>
        /// <returns></returns>
        public DataTable GetTableSchem(bool isTestRecord)
        {
            DataTable dt = new DataTable();
            if (isTestRecord)
            {
                dt.Columns.AddRange(new DataColumn[]{
                    new DataColumn("设备编号",typeof(string)),
                    new DataColumn("测试时间", typeof(DateTime)),
                    new DataColumn("测试项目", typeof(string)),
                    new DataColumn("单位", typeof(string)),
                    new DataColumn("指标要求", typeof(string)),
                    new DataColumn("测试值", typeof(string)),
                    new DataColumn("测试结果", typeof(string)),
                    new DataColumn("测试员", typeof(string)),
                    new DataColumn("模块类型", typeof(string))});
            }
            else
            {
                dt.Columns.AddRange(new DataColumn[]{
                    new DataColumn("机车属局", typeof(string)),
                    new DataColumn("机车属段", typeof(string)),
                    new DataColumn("机车属所", typeof(string)),
                    new DataColumn("机车编号", typeof(string)),
                    new DataColumn("机车端别", typeof(int)),
                    new DataColumn("机车修程", typeof(string)),
                    new DataColumn("CIR属局", typeof(string)),
                    new DataColumn("CIR属段", typeof(string)),
                    new DataColumn("CIR属车间", typeof(string)),
                    new DataColumn("CIR属工区", typeof(string)),
                    new DataColumn("CIR生产商", typeof(string)),
                    new DataColumn("CIR型号", typeof(string)),
                    new DataColumn("CIR编号", typeof(string)),
                    new DataColumn("CIR修程", typeof(string))});
            }
            return dt;
        }

        /// <summary>
        /// 查询测试记录
        /// </summary>
        /// <param name="device_num"></param>
        /// <returns></returns>
        public DataTable QueryData(string sql)
        {
            try
            {
                DataTable dt = new DataTable();
                connStr = "server =" + serverPath + ";database = testResult; User ID = sa; Password = " + Password;
                SqlConnection sqlConn = new SqlConnection(connStr);
                SqlCommand comm = new SqlCommand(sql, sqlConn);
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = comm;
                adapter.Fill(dt);
                sqlConn.Close();
                return dt;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        ///  根据wheresql删除tablename表中的数据
        /// </summary>
        /// <param name="wheresql"></param>
        /// <param name="tablename"></param>
        public void DeleteSql(string wheresql, string tablename)
        {
            DataTable dt = new DataTable();
            connStr = "server =" + serverPath + ";database = testResult; User ID = sa; Password = " + Password;
            SqlConnection sqlConn = new SqlConnection(connStr);
            StringBuilder sb = new StringBuilder();
            sb.Append("delete from ");
            sb.Append(tablename);
            sb.Append(" ");
            sb.Append(wheresql);
            ExecuteSql(connStr, sb.ToString());
        }
        /// <summary>
        /// 查询已测试过的设备编号
        /// </summary>
        /// <returns></returns>
        public DataTable QueryDevice()
        {
            DataTable dt = new DataTable();
            connStr = "server =" + serverPath + ";database = testResult; User ID = sa; Password = " + Password;
            SqlConnection sqlConn = new SqlConnection(connStr);
            string sql = "select CIR编号 from deviceInfo";
            SqlCommand comm = new SqlCommand(sql, sqlConn);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = comm;
            adapter.Fill(dt);
            sqlConn.Close();
            return dt;
        }
        /// <summary>
        /// 创建单项测试全部导出数据表
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="module"></param>
        /// <param name="existUnit"></param>
        /// <returns></returns>
        public DataTable CreateSingleTestExportTable(DataGridView dgv, string module, bool existUnit)
        {
            DataTable dt2 = new DataTable();
            if (dgv.Columns.Count > 2)
            {
                DataColumn col = new DataColumn("分类");
                dt2.Columns.Add(col);
                DataColumn col2 = new DataColumn("测试项目");
                dt2.Columns.Add(col2);
                DataColumn col3 = new DataColumn("单位");
                dt2.Columns.Add(col3);
                DataColumn col4 = new DataColumn("指标要求");
                dt2.Columns.Add(col4);
                DataColumn col5 = new DataColumn("测试值");
                dt2.Columns.Add(col5);
                DataColumn col6 = new DataColumn("测试结果");
                dt2.Columns.Add(col6);
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["测试结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt2.NewRow();

                        dr[1] = dgv.Rows[i].Cells["测试项目"].Value.ToString();
                        if (existUnit)
                        {
                            dr[2] = dgv.Rows[i].Cells["单位"].Value.ToString();
                        }
                        else
                        {
                            dr[2] = "";
                        }
                        dr[3] = dgv.Rows[i].Cells["指标要求"].Value.ToString();
                        dr[4] = dgv.Rows[i].Cells["测试值"].Value.ToString();
                        dr[5] = dgv.Rows[i].Cells["测试结果"].Value.ToString();
                        dr[0] = module;
                        dt2.Rows.Add(dr);
                    }
                }
            }
            else
            {
                DataColumn col = new DataColumn("分类");
                dt2.Columns.Add(col);
                DataColumn col2 = new DataColumn("测试项目");
                dt2.Columns.Add(col2);
                DataColumn col3 = new DataColumn("测试结果");
                dt2.Columns.Add(col3);
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["试验结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt2.NewRow();
                        dr[0] = module;
                        dr[1] = dgv.Rows[i].Cells["试验项目"].Value.ToString();
                        dr[2] = dgv.Rows[i].Cells["试验结果"].Value.ToString();
                        dt2.Rows.Add(dr);
                    }
                }
            }
            return dt2;
        }

        /// <summary>
        ///保存单项测试结果 
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="testTime"></param>
        /// <param name="tester"></param>
        /// <param name="module"></param>
        /// <param name="dev_num"></param>
        /// <param name="isHaveChecked"></param>
        /// <returns></returns>
        public bool SaveData(DataGridView dgv, string testTime, string tester, string module, string dev_num, ref List<DataTable> dataTable, bool existUnit, bool saveAll)//
        {
            DataTable dt = GetTableSchem(true);
            if (dgv.Columns.Count > 2)
            {
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["测试结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt.NewRow();

                        dr[0] = dev_num;
                        dr[1] = Convert.ToDateTime(testTime);
                        dr[2] = dgv.Rows[i].Cells["测试项目"].Value.ToString();
                        if (existUnit)
                        {
                            dr[3] = dgv.Rows[i].Cells["单位"].Value.ToString();
                        }
                        else
                        {
                            dr[3] = "";
                        }
                        dr[4] = dgv.Rows[i].Cells["指标要求"].Value.ToString();
                        dr[5] = dgv.Rows[i].Cells["测试值"].Value.ToString();
                        dr[6] = dgv.Rows[i].Cells["测试结果"].Value.ToString();
                        dr[7] = tester;
                        dr[8] = module;
                        dt.Rows.Add(dr);
                    }
                }
            }
            else
            {
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["试验结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt.NewRow();

                        dr[0] = dev_num;
                        dr[1] = Convert.ToDateTime(testTime);
                        dr[2] = dgv.Rows[i].Cells["试验项目"].Value.ToString();
                        dr[3] = "";
                        dr[4] = "";
                        dr[5] = "";
                        dr[6] = dgv.Rows[i].Cells["试验结果"].Value.ToString();
                        dr[7] = tester;
                        dr[8] = module;
                        dt.Rows.Add(dr);
                    }
                }
            }
            bool result = RestoreData(dt, "test_rec");
            if (!saveAll)
            {
                if (result)
                    MessageBox.Show("数据保存成功！");
                else
                    MessageBox.Show("数据保存失败！");
            }
            return result;
        }

        /// <summary>
        /// 创建全部导出整机测试结果的数据表
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="existUnit"></param>
        /// <returns></returns>
        public DataTable CreateTotalTestExportTable(DataGridView dgv, bool existUnit)
        {
            DataTable dt2 = new DataTable();
            if (dgv.Columns.Count > 3)
            {
                DataColumn col = new DataColumn("分类");
                dt2.Columns.Add(col);
                DataColumn col2 = new DataColumn("测试项目");
                dt2.Columns.Add(col2);
                DataColumn col3 = new DataColumn("单位");
                dt2.Columns.Add(col3);
                DataColumn col4 = new DataColumn("指标要求");
                dt2.Columns.Add(col4);
                DataColumn col5 = new DataColumn("测试值");
                dt2.Columns.Add(col5);
                DataColumn col6 = new DataColumn("测试结果");
                dt2.Columns.Add(col6);
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["测试结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt2.NewRow();

                        dr[1] = dgv.Rows[i].Cells["测试项目"].Value.ToString();
                        if (existUnit)
                        {
                            dr[2] = dgv.Rows[i].Cells["单位"].Value.ToString();
                        }
                        else
                        {
                            dr[2] = "";
                        }
                        dr[3] = dgv.Rows[i].Cells["指标要求"].Value.ToString();
                        dr[4] = dgv.Rows[i].Cells["测试值"].Value.ToString();
                        dr[5] = dgv.Rows[i].Cells["测试结果"].Value.ToString();
                        if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("发射机性能"))
                        {
                            dr[0] = "发射机性能指标";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("同频接收机性能"))
                        {
                            dr[0] = "同频接收机性能指标";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("异频接收机性能"))
                        {
                            dr[0] = "异频接收机性能指标";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("信令信号"))
                        {
                            dr[0] = "信令性能指标";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("GSM-R语音模块"))
                        {
                            dr[0] = "GSM-R语音模块指标";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("GSM-R数据模块"))
                        {
                            dr[0] = "GSM-R数据模块指标";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("866信道") || dgv.Rows[i].Cells["分类"].Value.ToString().Contains("821信道"))
                        {
                            dr[0] = "LBJ发射机电性能指标";
                        }
                        dt2.Rows.Add(dr);
                    }
                }
            }
            else
            {
                DataColumn col = new DataColumn("分类");
                dt2.Columns.Add(col);
                DataColumn col2 = new DataColumn("测试项目");
                dt2.Columns.Add(col2);
                DataColumn col3 = new DataColumn("测试结果");
                dt2.Columns.Add(col3);
                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["试验结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt2.NewRow();
                        dr[1] = dgv.Rows[i].Cells["试验项目"].Value.ToString();
                        dr[2] = dgv.Rows[i].Cells["试验结果"].Value.ToString();
                        dr[0] = dgv.Rows[i].Cells["分类"].Value.ToString();
                        dt2.Rows.Add(dr);
                    }
                }
            }
            return dt2;
        }

        /// <summary>
        /// 保存整机测试时的数据
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="tester"></param>
        /// <param name="module"></param>
        /// <param name="dev_num"></param>
        /// <returns></returns>
        public bool SaveData(DataGridView dgv, string testTime, string tester, string dev_num, ref List<DataTable> dataTable, bool existUnit)
        {
            DataTable dt = GetTableSchem(true);

            if (dgv.Columns.Count > 3)
            {

                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["测试结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt.NewRow();

                        dr[0] = dev_num;
                        dr[1] = Convert.ToDateTime(testTime);
                        dr[2] = dgv.Rows[i].Cells["测试项目"].Value.ToString();
                        if (existUnit)
                        {
                            dr[3] = dgv.Rows[i].Cells["单位"].Value.ToString();
                        }
                        else
                        {
                            dr[3] = "";
                        }
                        dr[4] = dgv.Rows[i].Cells["指标要求"].Value.ToString();
                        dr[5] = dgv.Rows[i].Cells["测试值"].Value.ToString();
                        dr[6] = dgv.Rows[i].Cells["测试结果"].Value.ToString();
                        dr[7] = tester;
                        if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("发射机性能"))
                        {
                            dr[8] = "450MHz发射机";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("同频接收机性能"))
                        {
                            dr[8] = "450MHz同频接收机";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("异频接收机性能"))
                        {
                            dr[8] = "450MHz异频接收机";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("信令信号"))
                        {
                            dr[8] = "450MHz信令";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("GSM-R语音模块"))
                        {
                            dr[8] = "GSM-R数据";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("GSM-R数据模块"))
                        {
                            dr[8] = "GSM-R语音";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("866信道发射机"))
                        {
                            dr[8] = "LBJ发射机";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("821信道发射机"))
                        {
                            dr[8] = "LBJ发射机";
                        }
                        else if (dgv.Rows[i].Cells["分类"].Value.ToString().Contains("866信道接收机"))
                        {
                            dr[8] = "LBJ接收机";
                        }

                        dt.Rows.Add(dr);
                    }
                }
            }
            else
            {

                for (int i = 0; i < dgv.RowCount; i++)
                {
                    if (dgv.Rows[i].Cells["试验结果"].Value.ToString() != "")
                    {
                        DataRow dr = dt.NewRow();

                        dr[0] = dev_num;
                        dr[1] = Convert.ToDateTime(testTime);
                        dr[2] = dgv.Rows[i].Cells["试验项目"].Value.ToString();
                        dr[3] = "";
                        dr[4] = "";
                        dr[5] = "";
                        dr[6] = dgv.Rows[i].Cells["试验结果"].Value.ToString();
                        dr[7] = tester;
                        dr[8] = dgv.Rows[i].Cells["分类"].Value.ToString();
                        dt.Rows.Add(dr);
                    }
                }
            }
            bool result = RestoreData(dt, "test_rec");
            return result;
        }

        #region    将测试结果保存为PDF

        private void SetFooter(PdfWriter writer)
        {
            PdfReportM1HeaderFooter headerFooter = new PdfReportM1HeaderFooter();
            writer.SetBoxSize("art", PageSize.A4);
            writer.PageEvent = headerFooter;
        }

        public bool ExportDataToPDF(string strCaption, List<DataTable> dataTable, string filePath)
        {
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Create);
                Document document = new Document(PageSize.A4);//创建一个Document实例
                document.NewPage();
                PdfWriter writer = PdfWriter.GetInstance(document, file);//创建Writer实例       
                this.SetFooter(writer);
                document.Open();
                BaseFont baseFont = CreateChineseFont();

                iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 20, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font fontUnderLine = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.UNDERLINE);
                iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 12);
                iTextSharp.text.Font normalRedFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL | iTextSharp.text.Font.BOLD, BaseColor.RED);
                float titleLineHeight = 45f, normalLineHeight = 25f;
                Paragraph pBlank = new Paragraph(" ", normalFont);
                pBlank.Leading = normalLineHeight;
                Paragraph titleP = new Paragraph(strCaption, titleFont);
                titleP.Leading = titleLineHeight; titleP.Alignment = Element.ALIGN_CENTER;
                document.Add(titleP);
                document.Add(pBlank);
                document.Add(CreateTable(dataTable));
                document.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ExportDataGridViewToPDF(string caption, DataGridView dgv, DeviceInfo device, string tester, bool haveCheckBox, string fileName)
        {
            Document document = new Document(PageSize.A4);//创建一个Document实例
            try
            {
                FileStream file = new FileStream(fileName, FileMode.OpenOrCreate);
                document.NewPage();
                PdfWriter writer = PdfWriter.GetInstance(document, file);//创建Writer实例      
                this.SetFooter(writer);
                document.Open();
                BaseFont baseFont = CreateChineseFont();

                iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 20, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font fontUnderLine = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.UNDERLINE);
                iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 12);
                iTextSharp.text.Font normalRedFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL | iTextSharp.text.Font.BOLD, BaseColor.RED);
                float titleLineHeight = 45f, normalLineHeight = 25f;
                Paragraph pBlank = new Paragraph(" ", normalFont);
                pBlank.Leading = normalLineHeight;
                Paragraph titleP = new Paragraph(caption, titleFont);
                titleP.Leading = titleLineHeight; titleP.Alignment = Element.ALIGN_CENTER;
                document.Add(titleP);
                document.Add(pBlank);
                document.Add(CreateTable(dgv, device, tester, haveCheckBox));
                document.Close();
                // MessageBox.Show("生成报表成功");
                return true;
            }
            catch
            {
                //MessageBox.Show("生成报表失败");
                document.Close();
                return false;
            }
        }

        /// <summary>
        /// 创建中文字体(实现中文)
        /// </summary>
        /// <returns></returns>
        public static BaseFont CreateChineseFont()
        {
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll"); //"STSong-Light", "UniGB-UCS2-H", 
            BaseFont baseFT = BaseFont.CreateFont(@"c:\windows\fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);


            //iTextSharp.text.Font font = new iTextSharp.text.Font(baseFT);
            return baseFT;
        }

        /// <summary>
        /// 创建Table行
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="txtFont">字体</param>
        /// <param name="colSpan">跨行数</param>
        /// <param name="padTop">顶部padding</param>
        /// <param name="padBottom">底部padding</param>
        /// <param name="bgColor">背景色</param>
        /// <returns>Table行</returns>
        static PdfPCell CreateCellHeader(string txt, iTextSharp.text.Font txtFont, int colSpan, float padTop, float padBottom, BaseColor bgColor)
        {
            PdfPCell cell = new PdfPCell(new Phrase(txt, txtFont));
            if (padTop > 0) { cell.PaddingTop = padTop; }
            if (padBottom > 0) { cell.PaddingBottom = padBottom; }
            if (colSpan > 0) { cell.Colspan = colSpan; }
            cell.HorizontalAlignment = Element.ALIGN_CENTER; //0=Left, 1=Centre, 2=Right
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            cell.BackgroundColor = bgColor;

            return cell;
        }

        /// <summary>
        /// 创建表格(PdfPTable)
        /// </summary>
        /// <returns></returns>
        private PdfPTable CreateTable(List<DataTable> dataTable)
        {
            bool haveAddHeadText = false;
            bool haveAddHeadText2 = false;
            PdfPTable table;
            table = new PdfPTable(6);
            table.TotalWidth = 470f;
            table.LockedWidth = true;
            table.HorizontalAlignment = 1;
            BaseFont baseFont = CreateChineseFont();
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 10), normalBoldFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font normalRedFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL | iTextSharp.text.Font.BOLD, BaseColor.RED);
            float padding = 6f; BaseColor bgColor = new BaseColor(153, 204, 255);
            table.AddCell(CreateCell("测试人员", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.MotherFrm.Tester, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("机车编号", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Cab_num, normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell("机车配属", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Cab_bur + "  铁路局   " + MainFrm.device.Cab_seg + "  段   " + MainFrm.device.Cab_pl + "  所", normalFont, 0, 4, padding, padding));
            table.AddCell(CreateCell("机车端别", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Cab_db.ToString(), normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("机车修程", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Cab_xc, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备生产商", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Dev_man, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备型号", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Dev_mod, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备编号", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Dev_num, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备修程", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Dev_xc, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备配属", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(MainFrm.device.Dev_bur + "  铁路局   " + MainFrm.device.Dev_seg + "  段   " + MainFrm.device.Dev_ws + "  车间   " + MainFrm.device.Dev_wa + "  工区", normalFont, 0, 4, padding, padding));
            if (dataTable.Count > 0)
            {
                for (int i = 0; i < dataTable.Count; i++)
                {
                    int rowCount = dataTable[i].Rows.Count;
                    int colCount = dataTable[i].Columns.Count;
                    string modName = dataTable[i].Rows[0]["分类"].ToString();

                    if (colCount > 3 && !haveAddHeadText)
                    {
                        for (int j = 0; j < dataTable[i].Columns.Count; j++)
                        {

                            string headerText = dataTable[i].Columns[j].ColumnName;
                            table.AddCell(CreateCellHeader(headerText, normalBoldFont, 0, padding, padding, bgColor));
                        }
                        table.HeaderRows = 1;
                        haveAddHeadText = true;
                        haveAddHeadText2 = false;
                    }
                    else if (colCount <= 3 && !haveAddHeadText2)
                    {
                        for (int j = 0; j < dataTable[i].Columns.Count; j++)
                        {

                            string headerText = dataTable[i].Columns[j].ColumnName;
                            table.AddCell(CreateCellHeader(headerText, normalBoldFont, 2, padding, padding, bgColor));
                        }
                        haveAddHeadText2 = true;
                        haveAddHeadText = false;
                    }

                    if (colCount > 3)
                    {
                        table.AddCell(CreateRowSpanCell(modName, normalBoldFont, rowCount, 0));
                        for (int k = 0; k < rowCount; k++)
                        {
                            for (int j = 1; j < colCount; j++)
                            {
                                table.AddCell(CreateCell(dataTable[i].Rows[k][j].ToString(), normalFont, 0, 0, padding, padding));
                            }
                        }
                    }
                    else
                    {
                        table.AddCell(CreateRowSpanCell(modName, normalBoldFont, rowCount, 2));
                        for (int j = 0; j < rowCount; j++)
                        {
                            for (int k = 1; k < colCount; k++)
                            {
                                table.AddCell(CreateCell(dataTable[i].Rows[j][k].ToString(), normalFont, 0, 2, padding, padding));
                            }
                        }
                    }
                }
            }
            return table;
        }

        public PdfPTable CreateTable(DevExpress.XtraGrid.Views.Grid.GridView dgv, DeviceInfo device, string tester)
        {
            PdfPTable table;
            table = new PdfPTable(dgv.Columns.Count);
            table.TotalWidth = 470f;
            table.LockedWidth = true;
            table.HorizontalAlignment = 1;
            int colCount = dgv.Columns.Count;
            int rowCount = dgv.RowCount;
            BaseFont baseFont = CreateChineseFont();
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 10), normalBoldFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font normalRedFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL | iTextSharp.text.Font.BOLD, BaseColor.RED);
            float padding = 6f; BaseColor bgColor = new BaseColor(153, 204, 255);
            table.AddCell(CreateCell("测试人员", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(tester, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("机车编号", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(device.Cab_num, normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell("机车配属", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(device.Cab_bur + "  铁路局   " + device.Cab_seg + "  段   " + device.Cab_pl + "  所", normalFont, 0, 4, padding, padding));
            table.AddCell(CreateCell("机车端别", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Cab_db.ToString(), normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("机车修程", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Cab_xc, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备生产商", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_man, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备型号", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_mod, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备编号", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_num, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备修程", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_xc, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备配属", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(device.Dev_bur + "  铁路局   " + device.Dev_seg + "  段   " + device.Dev_ws + "  车间   " + device.Dev_wa + "  工区", normalFont, 0, 4, padding, padding));
            for (int i = 0; i < colCount; i++)
            {
                string header = dgv.Columns[i].Caption;
                table.AddCell(CreateCellHeader(header, normalBoldFont, 0, padding, padding, bgColor));
            }
            table.HeaderRows = 1;
            int num = 1;
            string preStr = string.Empty;
            for (int i = 0; i < rowCount; i++)
            {
                // if (preStr == string.Empty)
                //{
                //    preStr = dgv.GetRowCellValue(i, dgv.Columns[colCount - 1]).ToString();
                //}
                //else
                //{
                //    if (preStr == dgv.GetRowCellValue(i, dgv.Columns[colCount - 1]).ToString())
                //    {
                //        num++;
                //        if (num == colCount)
                //        {
                //            table.AddCell(CreateRowSpanCell(preStr, normalBoldFont, num, 0));
                //        }
                //    }
                //    else
                //    {
                //        table.AddCell(CreateRowSpanCell(preStr, normalBoldFont, num, 0));
                //        preStr = dgv.GetRowCellValue(i, dgv.Columns[colCount - 1]).ToString();
                //        num = 1;
                //    }
                //}
                for (int j = 0; j < colCount; j++)
                {
                    table.AddCell(CreateCell(dgv.GetRowCellValue(i, dgv.Columns[j]).ToString(), normalFont, 0, 0, padding, padding));
                }
            }
            return table;
        }

        private PdfPTable CreateTable(DataGridView dgv, DeviceInfo device, string tester, bool isHaveCheckBox)
        {
            PdfPTable table;
            table = new PdfPTable(6);
            table.TotalWidth = 470f;
            table.LockedWidth = true;
            table.HorizontalAlignment = 1;
            BaseFont baseFont = CreateChineseFont();
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 10), normalBoldFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font normalRedFont = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL | iTextSharp.text.Font.BOLD, BaseColor.RED);
            float padding = 6f; BaseColor bgColor = new BaseColor(153, 204, 255);
            table.AddCell(CreateCell("测试人员", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(tester, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("机车编号", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(device.Cab_num, normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell("机车配属", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(device.Cab_bur + "  铁路局   " + device.Cab_seg + "  段   " + device.Cab_pl + "  所", normalFont, 0, 4, padding, padding));
            table.AddCell(CreateCell("机车端别", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Cab_db.ToString(), normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("机车修程", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Cab_xc, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备生产商", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_man, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备型号", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_mod, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备编号", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_num, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备修程", normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell(device.Dev_xc, normalFont, 0, 0, padding, padding));
            table.AddCell(CreateCell("CIR设备配属", normalFont, 0, 2, padding, padding));
            table.AddCell(CreateCell(device.Dev_bur + "  铁路局   " + device.Dev_seg + "  段   " + device.Dev_ws + "  车间   " + device.Dev_wa + "  工区", normalFont, 0, 4, padding, padding));
            int columnIndex = 0;
            if (isHaveCheckBox)
                columnIndex = 1;
            int columnNum = dgv.Columns.Count;
            for (int i = columnIndex; i < dgv.Columns.Count; i++)
            {
                string header = dgv.Columns[i].HeaderText;
                if (columnNum == 7)
                {
                    table.AddCell(CreateCellHeader(header, normalBoldFont, 0, padding, padding, bgColor));
                }
                else if (columnNum == 5 || columnNum == 6)
                {
                    if (header == "测试项目")
                    {
                        table.AddCell(CreateCellHeader(header, normalBoldFont, 2, padding, padding, bgColor));
                    }
                    else
                    {
                        table.AddCell(CreateCellHeader(header, normalBoldFont, 0, padding, padding, bgColor));
                    }
                }
                else if (columnNum == 4)
                {
                    if (header == "测试项目" || header == "指标要求")
                    {
                        table.AddCell(CreateCellHeader(header, normalBoldFont, 2, padding, padding, bgColor));
                    }
                    else
                    {
                        table.AddCell(CreateCellHeader(header, normalBoldFont, 0, padding, padding, bgColor));
                    }
                }
                else if (columnNum == 3)
                {
                    table.AddCell(CreateCellHeader(header, normalBoldFont, 2, padding, padding, bgColor));
                }
                else if (columnNum == 2)
                {
                    table.AddCell(CreateCellHeader(header, normalBoldFont, 3, padding, padding, bgColor));
                }
            }
            table.HeaderRows = 1;

            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                if (dgv.Columns.Count > 3)
                {
                    if (dgv.Rows[i].Cells["测试结果"].Value.ToString() == "")
                        continue;
                }
                else
                {
                    if (dgv.Rows[i].Cells["试验结果"].Value.ToString() == "")
                        continue;
                }
                int startColumnIndex = 0;
                if (isHaveCheckBox)
                    startColumnIndex = 1;
                for (int j = startColumnIndex; j < dgv.Columns.Count; j++)
                {
                    string header = dgv.Columns[j].HeaderText;
                    if (columnNum == 7)
                    {
                        table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 0, padding, padding));

                    }
                    else if (columnNum == 5 || columnNum == 6)
                    {
                        if (header == "测试项目")
                        {
                            table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 2, padding, padding));
                        }
                        else
                        {
                            table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 0, padding, padding));
                        }
                    }
                    else if (columnNum == 4)
                    {
                        if (header == "测试项目" || header == "指标要求")
                        {
                            table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 2, padding, padding));
                        }
                        else
                        {
                            table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 0, padding, padding));
                        }
                    }
                    else if (columnNum == 3)
                    {
                        table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 2, padding, padding));
                    }
                    else if (columnNum == 2)
                    {
                        table.AddCell(CreateCell(dgv.Rows[i].Cells[j].Value.ToString(), normalFont, 0, 3, padding, padding));
                    }
                }
            }
            return table;
        }

        /// <summary>
        /// 创建Table行
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="txtFont">字体</param>
        /// <param name="align">对齐方式</param>
        /// <param name="colSpan">跨列数</param>
        /// <param name="padTop">顶部padding</param>
        /// <param name="padBottom">底部padding</param>
        /// <returns>Table行</returns>
        static PdfPCell CreateCell(string txt, iTextSharp.text.Font txtFont, int align, int colSpan, float padTop, float padBottom)
        {
            PdfPCell cell = new PdfPCell(new Phrase(txt, txtFont));
            if (padTop > 0) { cell.PaddingTop = padTop; }
            if (padBottom > 0) { cell.PaddingBottom = padBottom; }
            if (colSpan > 0) { cell.Colspan = colSpan; }
            cell.HorizontalAlignment = align;
            return cell;
        }

        /// <summary>
        /// 创建Table行(RowSpan)
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="txtFont">字体</param>
        /// <returns>Table行(RowSpan)</returns>
        static PdfPCell CreateRowSpanCell(string txt, iTextSharp.text.Font txtFont, int rowSpan, int colSpan)
        {
            PdfPCell cell = new PdfPCell(new Phrase(60f, txt, txtFont));
            cell.Rowspan = rowSpan;
            cell.PaddingTop = 6f;
            cell.PaddingBottom = 6f;
            cell.PaddingLeft = 10f;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            cell.Colspan = colSpan;
            return cell;
        }
        #endregion
    }
}
